package org.iteam.xlz.core.service.message;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import org.iteam.commons.utils.DateUtil;
import org.iteam.core.utils.SqlBuilder;
import org.iteam.db.BaseService;
import org.iteam.xlz.core.entity.messages.Notices;

public class NoticeService extends BaseService<Notices>{
	static NoticeService instance;
	private NoticeService(){}
	
	public static NoticeService getInstance(){
		if(null==instance){
			instance=new NoticeService();
		}
		return instance;
	}
	
	public List<Notices> getUnNoticed(){
		try {
			return super.query("select * from notices where 1=1 and status=0 and now()<validatetime");
		} catch (SQLException e) {
			e.printStackTrace();
			return new ArrayList<Notices>();
		}
	}
	
	public long counts(){
		try {
			return super.counts("select count(1) from notices where 1=1");
		} catch (SQLException e) {
			e.printStackTrace();
			return 0;
		}
	}
	
	public List<Notices> query(long page,long rows){
		try {
			return super.query("select * from notices where 1=1 order by createtime desc limit ?,?",(page-1)*rows,rows);
		} catch (SQLException e) {
			e.printStackTrace();
			return new ArrayList<Notices>();
		}
	}
	
	public boolean create(Notices model){
		SqlBuilder sql=SqlBuilder.createInsert("notices");
		sql.addField("nid",UUID.randomUUID().toString().replace("-","").toUpperCase());
		sql.addField("title",model.getTitle());
		sql.addField("validatetime",model.getValidatetime());
		sql.addField("os",model.getOs());
		sql.addField("content",model.getContent());
		sql.addField("status",0);
		sql.addField("creator",model.getCreator());
		sql.addField("createtime",DateUtil.currentTime());
		try {
			return super.updates(sql.getSql(),sql.getParams())>0;
		} catch (SQLException e) {
			e.printStackTrace();
			return false;
		}
	}
	
	public boolean update(Notices model){
		SqlBuilder sql=SqlBuilder.createUpdate("notices");
		sql.addField("title",model.getTitle());
		sql.addField("validatetime",model.getValidatetime());
		sql.addField("os",model.getOs());
		sql.addField("status",model.getStatus());
		sql.addField("content",model.getContent());
		sql.addWhere("nid",model.getNid());
		try {
			return super.updates(sql.getSql(),sql.getParams())>0;
		} catch (SQLException e) {
			e.printStackTrace();
			return false;
		}
	}
	
	public Notices find(String nid){
		try { 
			return super.show("select * from notices where 1=1 and nid=?",nid);
		} catch (SQLException e) {
			e.printStackTrace();
			return new Notices();
		}
	}
	
	public boolean delete(String nid){
		try {
			return super.updates("delete from notices where 1=1 and nid=?",nid)>0;
		} catch (SQLException e) {
			e.printStackTrace();
			return false;
		}
	}
}